package com.lang.controller;

import com.lang.entity.Cart;
import com.lang.entity.User;
import com.lang.service.CartService;
import com.lang.service.impl.CartServiceImpl;
import com.lang.utils.StrUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
 * @Date : 2024/3/13 15:54
 * @Created by Lang
 * @ProjectName : LclShop
 */
@WebServlet("/cart")
public class CartServlet extends BaseServlet {

    private CartService cartService = new CartServiceImpl();

    // 添加购物车
    public String addCart(HttpServletRequest request, HttpServletResponse response) {
        String pid = request.getParameter("pid");
        String price = request.getParameter("price");
        User user = (User) request.getSession().getAttribute(StrUtils.lOG_USER);
        if (user == null) {
            request.setAttribute("msg", "请登录后再加入购物车");
            return StrUtils.FORWARD + "/login.jsp";
        }
        // 创建购物车
        int res = cartService.addCart(user.getU_id(), pid, price);
        return StrUtils.FORWARD + "/cartSuccess.jsp";
    }

    // 展示购物车
    public String showCart(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute(StrUtils.lOG_USER);
        if (user == null) {
            request.setAttribute("msg", "加入购物车前,需要登录!");
            return StrUtils.FORWARD + "/login.jsp";
        }
        List<Cart> list = cartService.getCarts(user.getU_id());
        request.setAttribute("carts", list);
        return StrUtils.FORWARD + "/cart.jsp";

    }


    // 购物车数量的加减
    public String updateCartNum(HttpServletRequest request, HttpServletResponse response) {

        String cid = request.getParameter("cid");
        String price = request.getParameter("price");
        String num = request.getParameter("num");
        int i = cartService.updateCartNum(cid, price, num);
        return StrUtils.REDIRECT + "cart?action=showCart";
    }

    //删除购物车
    public String deleteCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        int res = cartService.deleteCart(cid);
        return StrUtils.REDIRECT + "cart?action=showCart";
    }

    // 清空购物车
    public void clearCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        User user = (User) request.getSession().getAttribute(StrUtils.lOG_USER);
        int res = cartService.clearCart(user.getU_id());
        System.out.println("删除购物车=" + res);

        request.getRequestDispatcher("/cart?action=showCart").forward(request, response);
    }
}
